package b1.mobile.blackberry.ui.component;

import b1.mobile.blackberry.ui.component.util.FontFactory;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.BitmapField;

public class TabField extends BitmapField {
	private Bitmap normalPicImage;
	private Bitmap tabFocusPicImage;
	private Bitmap selectImage;

	private Bitmap icon;
	private String text;

	private boolean check;

	private int fieldIndex;

	public TabField(Bitmap normalPicImage, Bitmap tabFocusPicImage,
			Bitmap selectImage, Bitmap icon) {
		super(normalPicImage, Field.FOCUSABLE);
		this.normalPicImage = normalPicImage;
		this.tabFocusPicImage = tabFocusPicImage;
		this.selectImage = selectImage;
		this.icon = icon;
		this.text = null;
	}

	public TabField(Bitmap normalPicImage, Bitmap tabFocusPicImage,
			Bitmap selectImage, Bitmap icon, String text) {
		super(normalPicImage, Field.FOCUSABLE);
		this.normalPicImage = normalPicImage;
		this.tabFocusPicImage = tabFocusPicImage;
		this.selectImage = selectImage;
		this.icon = icon;
		this.text = text;
	}

	protected void paint(Graphics graphics) {
		super.paint(graphics);

		int width = icon.getWidth();
		int fullWidth = normalPicImage.getWidth();
		int height = icon.getHeight();
		int fullHeight = normalPicImage.getHeight();
		int iconX = fullWidth / 2 - width / 2;
		int iconY = fullHeight / 2 - height / 2 - 10;
		
		graphics.drawBitmap(iconX, iconY, width, height, icon, 0, 0);
		
		if (text != null) {
			graphics.setFont(FontFactory.getFont(Font.BOLD, 6));
			int fontX = (normalPicImage.getWidth() - graphics.getFont()
					.getAdvance(text)) / 2;
			int fontY = iconY + icon.getHeight();
			graphics.setColor(Color.WHITE);
			graphics.drawText(text, fontX, fontY);
		}
	}

	protected void onUnfocus() {
		if (check) {
			setBitmap(selectImage);
			invalidate();
		} else {
			setBitmap(normalPicImage);
			invalidate();
		}
	}

	protected void onFocus(int direction) {
		setBitmap(tabFocusPicImage);
		invalidate();
	}

	protected boolean navigationClick(int status, int time) {
		fieldChangeNotify(615212);
		return true;
	}

	protected void drawFocus(Graphics graphics, boolean on) {
	}

	public void setClick(boolean check) {
		this.check = check;
		if (check) {
			setBitmap(selectImage);
			invalidate();
		} else {
			setBitmap(normalPicImage);
			invalidate();
		}
	}

	public int getFieldIndex() {
		return fieldIndex;
	}

	public void setFieldIndex(int fieldIndex) {
		this.fieldIndex = fieldIndex;
	}

}
